package com.crud.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author wzm
 * @create 2023-05-04 10:24
 */
//专门用来打开和关闭资源的工具类
public class JDBCUtils {
    private static DataSource dataSource = null;

    static {
        try {
            //加载德鲁伊的资源
            Properties properties = new Properties();
            properties.load(
                    JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")
            );
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConn(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;//异常返回
    }


    /**
     * 关闭资源
     */
    public static  void closed(Connection connection, PreparedStatement pst, ResultSet rs){
        try {
            if(rs != null){
                rs.close();
            }
            if(pst != null){
                pst.close();
            }
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
